import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class MainFrame extends Frame 
{
    static final int C_P = 0;	// platform
    static final int C_S = 1;	// stair
    static final int C_M = 2;	// moving platform

    static final int C_Sucker = 3;	
    static final int C_Slope = 4;	
    static final int C_Press = 5;	
    static final int C_Lift = 6;	
    static final int C_Wall = 7;	

    static final int C_Trap = 11;	
    static final int C_Teleport = 12;	

    static final int C_Alien = 13; 
    static final int C_Bonus = 14; 
    static final int C_Static = 15; 
    static final int C_Man = 16; 

   	static final int C_S2 = 50;	// stair upper edges
   	static final int C_Sl2 = 51;	// slope upper edges

   	static Image bon = null;
   	static Image boff = null;

   	ButtonPanel p1 = null;
   	Image[][] imgs = null;


  int MAX_SUBTYPES = 10;

  Hashtable hp = null;
  Vector v,v1,v2;


  Color[] colors = null;

  Color areaColor = null;
  
  MenuBar mainMenu = null;
  Menu menuFile = null;
  MenuItem menuFileNew = null;
  MenuItem menuFileOpen = null;
  MenuItem menuFileSave = null;
  MenuItem menuFileExit = null;

  Button bExit = null;
  Button bSet = null;

  Checkbox cbFilter = null;
  Checkbox cbGrid = null;

  Menu menuHelp = null;
  MenuItem menuHelpAbout = null;

  EditorPanel pArea = null;
  Font font = null;

  JFileChooser fileChooser = null;


  TextField tfXSize = null;
  TextField tfYSize = null;

  Label lWidth = null;

  int area_width = 220;
  int area_height = 220;

  Vector vObjects = null;

  CObject obj = null,obj2 = null;

  int type;
  int subtype;

	static int activeType = 0;

	int i,j;

    static IFrame fB[] = null;
    static IFrame fS[] = null;
    static IFrame fM[] = null;
    static IFrame fW[] = null;
    static IFrame fSu[] = null;
    static IFrame fSl[] = null;
    static IFrame fPr[] = null;
    static IFrame fTr[] = null;
    static IFrame fLi[] = null;

	static IFrame fTrap[] = null;
	static IFrame fAlien[] = null;
	static IFrame fBonus[] = null;
	static IFrame fStatic[] = null;
	static IFrame fMan = null;

	public MainFrame() 
	{
		try 
		{
			init();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}

  void checkTypes()
  {
  	 type = p1.sy;
  	 subtype = p1.sx;
  }

  void addc(Component comp,int x,int y,int w,int h,Font font)
  {
     comp.setSize(w,h);
     comp.setLocation(x,y);
     comp.setFont(font);
     add(comp);
  }


  void init() throws Exception
  {
     areaColor = GetColor.gc(gp("area_color"));

     colors = new Color[MAX_SUBTYPES];
     for (int i = 0; i < MAX_SUBTYPES; i++)
     {
     	String str = gp("color" + i);
     	if (str != null)
     	{
     		colors[i] = GetColor.gc(str);
     	}
     	else
     	{
     		colors[i] = Color.white;
     	}
     }
 	 bon = Toolkit.getDefaultToolkit().createImage("Res\\Buttons\\bon.png");
 	 boff = Toolkit.getDefaultToolkit().createImage("Res\\Buttons\\boff.png");

 	 imgs = new Image[17][10];
 	 for (i = 0; i < imgs.length; i++) 
	 	 for (j = 0; j < imgs[0].length; j++) 
	 	 	imgs[i][j] = null;

     MediaTracker mt = new MediaTracker(this);

     mainMenu = new MenuBar();
     menuFile = new Menu("File");
     menuFileNew = new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
     menuFileOpen = new MenuItem("Open",new MenuShortcut(KeyEvent.VK_O));
     menuFileSave = new MenuItem("Save",new MenuShortcut(KeyEvent.VK_S));
     menuFileExit = new MenuItem("Exit",new MenuShortcut(KeyEvent.VK_Q));
     menuHelp = new Menu("Help");
     menuHelpAbout = new MenuItem("About");
     lWidth = new Label("");

     cbFilter = new Checkbox("Click filter",true);
     cbGrid = new Checkbox("Show grid",false);

     pArea = new EditorPanel(this);
     p1 = new ButtonPanel(this,20,20);

     bSet = new Button("Set");
     bExit = new Button("Exit");

     this.setLayout(null);
     this.setSize(450,400);
     this.setTitle("Level editor");
     this.setResizable(false);
     this.setBackground(GetColor.gc(gp("background_color")));

     tfXSize = new TextField(area_width + "");
     tfYSize = new TextField(area_height + "");

     font = new Font("Arial",0,12);

     pArea.addMouseListener(new Area_mouseAdapter(this));
     pArea.addMouseMotionListener(new Area_mouseMotionAdapter(this));
     pArea.addKeyListener(new Area_keyAdapter(this));

     p1.addMouseListener(new p1_mouseAdapter(this));
     p1.addMouseMotionListener(new p1_mouseMotionAdapter(this));

     menuFileNew.addActionListener(new MainFrame_menuFileNew_ActionAdapter(this));
     menuFileOpen.addActionListener(new MainFrame_menuFileOpen_ActionAdapter(this));
     menuFileSave.addActionListener(new MainFrame_menuFileSave_ActionAdapter(this));
     menuFileExit.addActionListener(new MainFrame_menuFileExit_ActionAdapter(this));
     menuHelpAbout.addActionListener(new MainFrame_menuHelpAbout_ActionAdapter(this));
     menuFile.add(menuFileNew);
     menuFile.add(menuFileOpen);
     menuFile.add(menuFileSave);
     menuFile.add(menuFileExit);
     menuHelp.add(menuHelpAbout);
     mainMenu.add(menuFile);
     mainMenu.add(menuHelp);

     addc(pArea,8,46,area_width,area_height,font);
     addc(p1,240,46,p1.aw,p1.ah,font);

     addc(bExit,8,366,80,20,font);

     addc(tfXSize,8,270,80,20,font);
     addc(tfYSize,8,294,80,20,font);
     addc(bSet,8,318,80,20,font);

     addc(cbFilter,130,270,80,20,font);
     addc(cbGrid,130,294,80,20,font);

//     addc(lWidth,480,166,80,20,font);

     this.setMenuBar(mainMenu);

     fileChooser = new JFileChooser();
     UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
 	 SwingUtilities.updateComponentTreeUI(fileChooser);
 	 fileChooser.setMultiSelectionEnabled(false);
 	 fileChooser.setCurrentDirectory(new File("Maps/"));
 	 fileChooser.removeChoosableFileFilter((fileChooser.getChoosableFileFilters())[0]);
 	 fileChooser.addChoosableFileFilter(new EditorFileFilter("map","Level map file"));

 	 vObjects = new Vector();

 	 initFrames();

     pArea.start();
     p1.start();
  }

	void initFrames()
	{
		bg = gf("bg0");

    	fB = new IFrame[120];
    	fS = new IFrame[12];
    	fM = new IFrame[6];

    	fW = new IFrame[6];
    	fSu = new IFrame[6];
    	fSl = new IFrame[7];
    	fPr = new IFrame[6];
    	fTr = new IFrame[4];
    	fLi = new IFrame[4];

    	fTrap = new IFrame[4];
    	fAlien = new IFrame[8];
    	fBonus = new IFrame[10];
    	fStatic = new IFrame[10];

		for (i = 0; i < 36; i++) fB[i] = gf("b" + i);
		imgs[0][0] = fB[0].getIcon(0);
		imgs[0][1] = fB[6].getIcon(0);
		imgs[0][2] = fB[12].getIcon(0);
		imgs[0][3] = fB[18].getIcon(0);
		imgs[0][4] = fB[24].getIcon(0);
		imgs[0][5] = fB[30].getIcon(0);

		for (i = 0; i < 2; i++)
		{
			if ((fS[i + i] = gf("s" + i + ".0")) != null)
				imgs[1][i] = fS[i + i].getIcon(0);
			fS[i + i + 1] = gf("s" + i + ".1");
		}

		for (i = 0; i < 1; i++) 
		{
			if ((fM[i] = gf("mv"+i)) != null)
				imgs[2][i] = fM[i].getIcon(0);
		}
		for (i = 0; i < 1; i++)
		{
			if ((fW[i + i] = gf("w" + i + ".0")) != null)
				imgs[7][i] = fW[i + i].getIcon(0);
			fW[i + i + 1] = gf("w" + i + ".1");
		}
		for (i = 0; i < 1; i++)
		{
			if ((fSu[i * 6] = gf("su" + i + ".0")) != null)
				imgs[3][i] = fSu[i * 6].getIcon(0);
			fSu[i * 6 + 1] = gf("su" + i + ".1");
			fSu[i * 6 + 2] = gf("su" + i + ".2");
			fSu[i * 6 + 3] = gf("su" + i + ".3");
			fSu[i * 6 + 4] = gf("su" + i + ".4");
			fSu[i * 6 + 5] = gf("su" + i + ".5");
		}
		for (i = 0; i < 1; i++)
		{
			if ((fSl[i * 7] = gf("sl" + i + ".0")) != null)
				imgs[4][i] = fSl[i * 7].getIcon(0);
			fSl[i * 7 + 1] = gf("sl" + i + ".1");
			fSl[i * 7 + 2] = gf("sl" + i + ".2");
			fSl[i * 7 + 3] = gf("sl" + i + ".3");
			fSl[i * 7 + 4] = gf("sl" + i + ".4");
			fSl[i * 7 + 5] = gf("sl" + i + ".5");
			fSl[i * 7 + 6] = gf("sl" + i + ".6");
		}
		for (i = 0; i < 1; i++)
		{
			if ((fPr[i + i] = gf("pr" + i + ".0")) != null)
				imgs[5][i] = fPr[i + i].getIcon(0);
			fPr[i + i + 1] = gf("pr" + i + ".1");
		}
		for (i = 0; i < 1; i++)
		{
			if ((fTr[i + i] = gf("te" + i + ".0")) != null)
				imgs[12][i] = fTr[i + i].getIcon(0);
			fTr[i + i + 1] = gf("te" + i + ".1");
		}
		for (i = 0; i < 1; i++)
		{
			if ((fLi[i + i] = gf("li" + i + ".0")) != null)
				imgs[6][i] = fLi[i + i].getIcon(0);
			fLi[i + i + 1] = gf("li" + i + ".1");
		}
		for (i = 0; i < 2; i++)
		{
			if ((fTrap[i] = gf("tr" + i)) != null)
				imgs[11][i] = fTrap[i].getIcon(1);
		}

		for (i = 0; i < 2; i++)
		{
			if ((fAlien[i] = gf("a" + i)) != null)
				imgs[13][i] = fAlien[i].getIcon(0);
		}
		for (i = 0; i < 7; i++)
		{
			if ((fBonus[i] = gf("bo" + i)) != null)
				imgs[14][i] = fBonus[i].getIcon(0);
		}
		for (i = 0; i < 1; i++)
		{
			if ((fStatic[i] = gf("st" + i)) != null)
				imgs[15][i] = fStatic[i].getIcon(0);
		}
		if ((fMan = gf("man")) != null)
			imgs[16][0] = fMan.getIcon(0);
	}

	Graphics goff = null;

	void draw(Graphics g)
	{
		goff = g;
		num = 0;
		drawType(C_Wall);
		drawType(C_Slope);
		drawType(C_Sucker);
		drawType(C_Teleport);
		drawType(C_S);
		drawType(C_P);
		drawType(C_Sl2);
		drawType(C_S2);
		drawType(C_M);
		drawType(C_Press);
		drawType(C_Lift);
		drawType(C_Trap);
		drawType(C_Static);
		drawType(C_Bonus);
		drawType(C_Alien);
		drawType(C_Man);
	}

    void drawP()
    {
    	goff.setClip(obj.x1,0,obj.x2 - obj.x1 + 4,area_height);
		for (j = obj.x1, x = obj.x1, y = obj.y1 + obj.disp, k = 0;
			j < obj.x2;
			j += 10, x += 10, y += obj.k, k++)
		{
			frm = fB[obj.imageIndex];
   			if (frm != null)
   			{
   				goff.drawImage(frm.image,x,y,null);
   			}
   		}
    }

    void drawS2()
    {
		frm = fS[(obj.subtype << 1) + 1];
		if (frm != null)
		{
    		dy = frm.h;
			x = obj.x1 - (frm.w >> 1);
			goff.setClip(0,obj.ymin,area_width,obj.ymax - obj.ymin);
			for (y1 = 0, y = obj.ymin; y1 < 12; y += dy, y1 += dy) goff.drawImage(frm.image,x,y,null);
		}
    }

    int x,y,x1,y1,x2,y2,dx,dy,k,ym,num;
    void drawType(int c_t)
    {
		for (i = 0; i < vObjects.size(); i++)
		{
			try
			{
				obj = obj2 = (CObject)(vObjects.elementAt(i));

                /*
				if (obj.type == c_t)
				{
					if (++obj.bc > 10) obj.bc = 0;
					if ((obj.bc == 0) && obj.selected) continue;
				}
                */

				if ((c_t == C_P) && (obj.type == C_P)) drawP();
				else
				if ((c_t == C_S) && (obj.type == C_S))
				{
		    		frm = fS[obj.subtype << 1];
		    		if (frm != null)
		    		{
			    		dy = frm.h;
		    			x = obj.x1 - (frm.w >> 1);
		    			goff.setClip(0,obj.ymin + 2,area_width,obj.ymax - obj.ymin);
						for (y1 = obj.ymin, y = obj.ymin; y1 < obj.ymax; y += dy, y1 += dy) 
							goff.drawImage(frm.image,x,y,null);
					}
				}
				else
				if ((c_t == C_S2) && (obj.type == C_S)) drawS2();
				else
				if ((c_t == C_Wall) && (obj.type == C_Wall))
				{
					dy = 0;
		    		frm = fW[obj.subtype << 1];
		    		if (frm != null)
		    		{
			    		dy = frm.h;
		    			x = obj.x1 - (frm.w >> 1);
		    			goff.setClip(0,obj.ymin,area_width,obj.ymax - obj.ymin);
						goff.drawImage(frm.image,x,obj.ymin,null);
					}
	    			frm = fW[(obj.subtype << 1) + 1];
	    			if (frm != null)
	    			{
	    				x = obj.x1 - (frm.w >> 1);
	    					goff.setClip(0,obj.ymin + dy,area_width,obj.ymax - obj.ymin - dy);
			    		dy = frm.h;
						for (y1 = obj.ymin, y = obj.ymin; y1 < obj.ymax; y += dy, y1 += dy) 
							goff.drawImage(frm.image,x,y,null);
					}
				}
				else
				if ((c_t == C_Press) && (obj.type == C_Press))
				{
					goff.setClip(0,obj.y1,area_width,obj.y2 - obj.y1 - 4);
					frm = fPr[(obj.subtype << 1) + 1];
					if (frm != null)
						for (y = obj.y1, j = obj.y1; y < obj.y2; y += frm.fh, j += frm.fh) 
							goff.drawImage(frm.image,obj.x1 - (frm.fw >> 1),j,null);
					goff.setClip(0,obj.y1,area_width,obj.y2 - obj.y1);
					frm = fPr[obj.subtype << 1];
					if (frm != null)
						goff.drawImage(frm.image,obj.x1 - (frm.fw >> 1),obj.y2 - frm.fh,null);
				}
				else
				if ((c_t == C_Lift) && (obj.type == C_Lift))
				{
					goff.setClip(0,obj.y1,area_width,obj.y2 - obj.y1 - obj.fh);
					frm = fLi[(obj.subtype << 1) + 1];
					if (frm != null)
						for (y = obj.y1; y < obj.y2; y += frm.h) 
							goff.drawImage(frm.image,obj.x1 - (frm.w >> 1),y,null);
					goff.setClip(0,obj.y1,area_width,obj.y2 - obj.y1);
					frm = fLi[obj.subtype << 1];
					if (frm != null)
					{
						goff.drawImage(frm.image,obj.x1 - (frm.w >> 1),obj.y1,null);
						goff.drawImage(frm.image,obj.x1 - (frm.w >> 1),obj.y2 - frm.h,null);
					}
				}
				else
				if ((c_t == C_Sucker) && (obj.type == C_Sucker))
				{
					x1 = obj.x1;
					y1 = obj.y1;
					x2 = obj.x2;
					y2 = obj.y2;
					ym = obj.ymin - 20;
					dx = 0;
					frm = fSu[obj.subtype * 6];
					if (frm != null)
					{
						goff.setClip(0,ym,area_width,y1 - ym - 3);
						for (y = ym; y <= y1; y += frm.h) goff.drawImage(frm.image,x1 - (frm.w >> 1),y,null);
						goff.setClip(0,ym,area_width,y2 - ym - 3);
						for (y = ym; y <= y2; y += frm.h) goff.drawImage(frm.image,x2 - (frm.w >> 1),y,null);
					}
					frm = fSu[obj.subtype * 6 + 3];
					if (frm != null)
					{
						goff.setClip(obj.xmin,0,obj.xmax - obj.xmin,area_height);
						for (x = obj.xmin; x <= obj.xmax; x += frm.w) goff.drawImage(frm.image,x,ym - (frm.h >> 1),null);
					}
					frm = fSu[obj.subtype * 6 + 4];
					if (frm != null)
					{
						goff.setClip(0,0,area_width,area_height);
						goff.drawImage(frm.image,obj.xmin - (frm.w >> 1),ym - (frm.h >> 1),null);
					}
					frm = fSu[obj.subtype * 6 + 2];
					if (frm != null)
					{
						goff.setClip(0,0,area_width,area_height);
						goff.drawImage(frm.image,obj.xmax - (frm.w >> 1),ym - (frm.h >> 1),null);
					}
					frm = fSu[obj.subtype * 6 + 1];
					if (frm != null)
					{
						goff.setClip(0,0,area_width,area_height);
						goff.drawImage(frm.image,obj.x1 - (frm.w >> 1),y1 - frm.h,null);
					}
					frm = fSu[obj.subtype * 6 + 5];
					if (frm != null)
					{
						goff.setClip(0,0,area_width,area_height);
						goff.drawImage(frm.image,obj.x2 - (frm.w >> 1),y2 - frm.h,null);
					}
				}
				else
				if ((c_t == C_Slope) && (obj.type == C_Slope))
				{
					x1 = obj.x1 - 7 - (obj.k < 0 ? 13 : 0);
			    	goff.setClip(0,obj.ymin,area_height,obj.ymax - obj.ymin);
			    	frm = fSl[obj.subtype * 4 + obj.imageIndex];
			    	dx = obj.k * frm.h;
			    	if (frm != null)
			    	for (j = obj.y1, x = x1; j < obj.y2; j += frm.h, x += dx)
			    	{
						goff.drawImage(frm.image,x,j,null);	
			    	}
				}
				else
				if ((c_t == C_Sl2) && (obj.type == C_Slope))
				{
					x1 = obj.x1 - 7 - (obj.k < 0 ? 13 : 0);
			    	goff.setClip(0,obj.ymin,area_height,obj.ymax - obj.ymin);
			    	frm = fSl[obj.subtype * 4 + obj.imageIndex + 3];
			    	dx = obj.k * frm.h;
			    	if (frm != null)
			    	for (j = obj.y1, x = x1; j < obj.y2; j += frm.h, x += dx)
			    	{
						goff.drawImage(frm.image,x,j,null);		    				
			    	}
			    	goff.setClip(0,obj.ymin,area_height,obj2.ymax - obj.ymin);
			    	if (obj.k == 0) 
			    	{
			    		frm = fSl[obj.subtype * 4 + 6];
//						goff.drawImage(frm.image,x1,obj.y1,20);		    				
			    	}
			    	else
			    		frm = fSl[obj.subtype * 4 + obj.imageIndex];
			    	if (frm != null)
			    	{
						goff.drawImage(frm.image,x1,obj.y1,null);		    				
			    	}
				}
				else
				if ((c_t == C_M) && (obj.type == C_M))
				{
	   		 		goff.setClip(0,0,area_width,area_height);
	   		 		goff.setColor(Color.white);
	   		 		goff.drawLine(obj.x1,obj.y1,obj.x2,obj.y2);
    				frm = fM[obj.subtype];
    				if (frm != null)
    				{
    					x1 = obj.x1 - (frm.fw >> 1);
			   			y1 = obj.y1;
    					x2 = obj.x2 - (frm.fw >> 1);
			   			y2 = obj.y2;
			   			goff.setClip(x1,y1,frm.fw,frm.fh);
			   			goff.drawImage(frm.image,x1,y1,null);
			   			goff.setClip(x2,y2,frm.fw,frm.fh);
			   			goff.drawImage(frm.image,x2,y2,null);
	   		 		}
				}
				else
				if ((c_t == C_Trap) && (obj.type == C_Trap))
				{
					frm = fTrap[obj.subtype];
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - frm.fh;
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x - frm.fw,y,null);
			    	}
				}
				else
				if ((c_t == C_Teleport) && (obj.type == C_Teleport))
				{
					frm = fTr[obj.subtype << 1];
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - (y1 = frm.fh);
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x,y,null);
								
						frm = fTr[(obj.subtype << 1) + 1];
						if (frm != null)
						{
							x = obj.x1 - (frm.fw >> 1);
							y = obj.y1 - y1 + 1;
							goff.setClip(x,y,frm.fw,frm.fh);
							goff.drawImage(frm.image,x - frm.fw * (num++),y,null);		    				
				    	}
			    	}
				}
				else
				if ((c_t == C_Trap) && (obj.type == C_Trap))
				{
					frm = fTrap[obj.subtype];
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - frm.fh;
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x,y,null);
			    	}
				}
				else
				if ((c_t == C_Alien) && (obj.type == C_Alien))
				{
					frm = fAlien[obj.subtype];
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - frm.fh;
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x,y,null);
			    	}
				}
				else
				if ((c_t == C_Bonus) && (obj.type == C_Bonus))
				{
					frm = fBonus[obj.subtype];
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - frm.fh;
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x,y,null);
			    	}
				}
				else
				if ((c_t == C_Static) && (obj.type == C_Static))
				{
					frm = fStatic[obj.subtype];
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - frm.fh;
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x,y,null);
			    	}
				}
				else
				if ((c_t == C_Man) && (obj.type == C_Man))
				{
					frm = fMan;
					if (frm != null)
					{
						x = obj.x1 - (frm.fw >> 1);
						y = obj.y1 - frm.fh;
						goff.setClip(x,y,frm.fw,frm.fh);
						goff.drawImage(frm.image,x,y,null);
			    	}
				}
			}
			catch(Exception ex)
			{
//				ex.printStackTrace();
			}
		}
    }

  CObject checkActive(int mx,int my)
  {
  	 CObject obj,actObj = null;
     for (int i = 0; i < vObjects.size(); i++)
  	 {
        obj = (CObject)vObjects.elementAt(i);
        if ((obj.type == activeType) || (!(cbFilter.getState())))
	        if (obj.checkActive(mx,my)) 
	        	actObj = obj;
     }
     return actObj;
  }

	void mouseMovedOnp1(MouseEvent e)
	{
		p1.mouseMoved(e.getX(),e.getY());
	}

	void mouseDraggedOnp1(MouseEvent e)
	{
		p1.mouseMoved(e.getX(),e.getY());
		p1.mousePressed(e.getX(),e.getY());
		typeChanged();			
	}

	void mousePressedOnp1(MouseEvent e)
	{
		p1.mousePressed(e.getX(),e.getY());
		typeChanged();			
	}

	void typeChanged()
	{
		activeType = p1.sy;
		pArea.redraw();
	}


	void mouseReleasedOnp1(MouseEvent e)
	{
	}

  CObject activeObject = null;
  CObject selectedObject = null;
  void mouseMovedOnArea(MouseEvent e)
  {
     int mx = e.getX();
     int my = e.getY();
     activeObject = checkActive(mx,my);
 	 if (activeObject instanceof CLine)
	 	 lWidth.setText(Math.abs(((CLine)activeObject).a[0].x - ((CLine)activeObject).a[1].x) + "");
 	 if (activeObject instanceof CPath)
	 	 lWidth.setText(Math.abs(((CPath)activeObject).a[0].x - ((CPath)activeObject).a[1].x) + "");
     pArea.redraw();
  }

  boolean isMousePressed = false;

  void keyPressedOnArea(KeyEvent e)
  {
     if (e.getKeyCode() == KeyEvent.VK_DELETE)
     {
     	if (activeObject != null)
     	{
     		int index = vObjects.indexOf(activeObject);
 			if (index != -1) vObjects.removeElementAt(index);
 			pArea.redraw();
     	}
     }
     char c = e.getKeyChar();
     if ((c >= '0') && (c <= '9') && (selectedObject != null))
     {
     	int index = (int)(c - '1');
     	if (c == '0') index = 9;
     	selectedObject.subtype = index;
		selectedObject.color = colors[index];
		pArea.redraw();
     }
  }

  CObject newObject = null;
  void mouseDraggedOnArea(MouseEvent e)
  {
     if (isMousePressed)
     {
//        mouseMovedOnArea(e);
        int mx = e.getX();
        int my = e.getY();
        if (mx < 0) return;
        if (mx > area_width) return;
        if (my < 0) return;
        if (my > area_height) return;
        if (activeObject != null)
        {
          	activeObject.move(mx,my,start_x,start_y);
          	if (activeObject instanceof CLine)
				lWidth.setText(Math.abs(((CLine)activeObject).a[0].x - ((CLine)activeObject).a[1].x) + "");
          	if (activeObject instanceof CPath)
				lWidth.setText(Math.abs(((CPath)activeObject).a[0].x - ((CPath)activeObject).a[1].x) + "");
          	start_x = mx;
          	start_y = my;
  	        pArea.redraw();
        }
        else
        {
        	if ((mx != start_x) || (my != start_y))	
        	{
        		if (newObject == null)
        		{
        			switch (type)
        			{
        				case 0:
							newObject = new CLine(type,subtype,start_x,start_y,mx,my);
							newObject.color = colors[subtype];
							vObjects.addElement(newObject);
							break;
						case 1:
						case 5:	// press
						case 6:	// lift
						case 7:	// wall
							newObject = new CStair(type,subtype,start_x,start_y,my);
							newObject.color = colors[subtype];
							vObjects.addElement(newObject);
							break;

						case 2:
							newObject = new CPath(type,subtype,start_x,start_y,mx,my);
							newObject.color = colors[subtype];
							vObjects.addElement(newObject);
							break;
						case 3: 
							newObject = new CSucker(type,subtype,start_x,start_y,mx,my);
							newObject.color = colors[subtype];
							vObjects.addElement(newObject);
							break;
						case 4: 
							newObject = new CSlope(type,subtype,start_x,start_y,mx,my);
							newObject.color = colors[subtype];
							vObjects.addElement(newObject);
							break;

						default:break;				
					}
				}
				else
				{
					if (newObject instanceof CLine)
					{
						((CLine)newObject).moveAnchor(1,mx,my);
						lWidth.setText(Math.abs(((CLine)newObject).a[0].x - ((CLine)newObject).a[1].x) + "");
					}
					if (newObject instanceof CStair) ((CStair)newObject).moveAnchor(1,mx,my);
					if (newObject instanceof CSlope) ((CSlope)newObject).moveAnchor(1,mx,my);
					if (newObject instanceof CSucker) ((CSucker)newObject).moveAnchor(1,mx,my);
					if (newObject instanceof CPath)
					{
						((CPath)newObject).moveAnchor(1,mx,my);
						lWidth.setText(Math.abs(((CPath)newObject).a[0].x - ((CPath)newObject).a[1].x) + "");
					}
					selectedObject = newObject;
					newObject.selected = true;
				}
        	}
        }
     }
  }

  void change()
  {
  	 selectedObject = null;
     for (int i = 0; i < vObjects.size(); i++)
     {
     	CObject obj = (CObject)vObjects.elementAt(i);
	    if (obj.selected = (activeObject == obj)) selectedObject = obj;
     }
  }

  int start_x = 0;
  int start_y = 0;
  
  void mousePressedOnArea(MouseEvent e)
  {
  	 checkTypes();
     isMousePressed = true;
     start_x = e.getX();
     start_y = e.getY();
     int w = 0;
     int h = 0;
     if (activeObject == null)
 	 if (newObject == null)
 	 {
		switch (type)
		{
			case C_Trap:
				w = fTrap[subtype].fw;
				h = fTrap[subtype].fh;
				break;
			case C_Teleport:
				w = fTr[subtype << 1].fw;
				h = fTr[subtype << 1].fh;
				break;
			case C_Alien:
				w = fAlien[subtype].fw;
				h = fAlien[subtype].fh;
				break;
			case C_Bonus:
				w = fBonus[subtype].fw;
				h = fBonus[subtype].fh;
				break;
			case C_Static:
				w = fStatic[subtype].fw;
				h = fStatic[subtype].fh;
				break;
			case C_Man:
				w = fMan.fw;
				h = fMan.fh;
				break;
			default:
				break;				
		}
		if (type >= C_Trap)
		{
			newObject = new CPoint(type,subtype,start_x,start_y);
			newObject.color = colors[subtype];
			newObject.fw = w >> 1;
			newObject.fh = h;
			vObjects.addElement(newObject);
		}
 	 }
     change();
  }

  void mouseReleasedOnArea(MouseEvent e)
  {
     isMousePressed = false;
     newObject = null;
  }

  void open()
  {
    fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
	int retval = fileChooser.showDialog(this, null);
	if (retval == JFileChooser.APPROVE_OPTION) 
	{
  	   File file = fileChooser.getSelectedFile();
  	   if (file != null) 
  	   {
          if (!file.isDirectory())
          {
             try
             {
             	vObjects = new Vector();
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int type;
                CObject obj = null;
                try
                {
                	area_width = in.readShort();
                	area_height = in.readShort();
                	tfXSize.setText(area_width+"");
                	tfYSize.setText(area_height+"");
                	pArea.setSize(area_width,area_height);
                    while ((type = (int)(in.readByte())) != -1)
                    {
                    	obj = null;
                    	try
                    	{
                    	switch(type)
                    	{
                    		case 0:obj = CLine.read(in,type); break;
                    		case 1:obj = CStair.read(in,type);break;
                    		case 2:obj = CPath.read(in,type); break;

                    		case 3:obj = CSucker.read(in,type);break;
                    		case 4:obj = CSlope.read(in,type);break;
                    		case 5:obj = CStair.read(in,type);break;
                    		case 6:obj = CStair.read(in,type);break;
                    		case 7:obj = CStair.read(in,type);break;
                    		case 8:
                    		case 9:
                    		case 10:break;

                    		case C_Trap:
                    			obj = CPoint.read(in,type);
                    			obj.fw = fTrap[subtype].fw >> 1;
                    			obj.fh = fTrap[subtype].fh;
                    			break;
                    		case C_Teleport:
                    			obj = CPoint.read(in,type);
                    			obj.fw = fTr[subtype << 1].fw >> 1;
                    			obj.fh = fTr[subtype << 1].fh;
                    			break;
                    		case C_Alien:
                    			obj = CPoint.read(in,type);
                    			obj.fw = fAlien[subtype].fw >> 1;
                    			obj.fh = fAlien[subtype].fh;
                    			break;
                    		case C_Bonus:
                    			obj = CPoint.read(in,type);
                    			obj.fw = fBonus[subtype].fw >> 1;
                    			obj.fh = fBonus[subtype].fh;
                    			break;
                    		case C_Static:
                    			obj = CPoint.read(in,type);
                    			obj.fw = fStatic[subtype].fw >> 1;
                    			obj.fh = fStatic[subtype].fh;
                    			break;
                    		case C_Man:
                    			obj = CPoint.read(in,type);
                    			obj.fw = fMan.fw >> 1;
                    			obj.fh = fMan.fh;
                    			break;

                    		default:obj = null;break;
                    	}
                    	}
                    	catch(Exception ex2)
                    	{
                    		System.out.println("Cant load object of type (" + type+")");
                    	}
                    	if (obj != null)
                    	{
                    		obj.color = colors[obj.subtype];
                    		vObjects.addElement(obj);
                    	}
                    }
                }
                catch(EOFException ex){}
                setTitle("Level editor - " + file);
                in.close();
                pArea.redraw();
             }
             catch(Exception ex)
             {
             	ex.printStackTrace();
                System.out.println("Can't open file " + file);
             }
          }
  	   }
	}
	pArea.repaint();
  }

  void saveType(int type) throws Exception
  {
     for (int i = 0; i < vObjects.size(); i++)
     {
        CObject obj = (CObject)vObjects.elementAt(i);
        if (obj != null)
        if (obj.type == type)
        {
        	System.out.println(obj.type + ":" + obj.subtype);
        	obj.write(out);
        }
     }
  }

  DataOutputStream out = null;
  void save()
  {
    fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
	int retval = fileChooser.showDialog(this, null);
	if (retval == JFileChooser.APPROVE_OPTION) 
	{
  	   File file = fileChooser.getSelectedFile();
  	   if (file != null) 
  	    if (!file.isDirectory())
   	    {
   	       if (!(file.getPath().toLowerCase().endsWith(".map"))) file = new File(file.getPath() + ".map");
   	       try
   	       {
              out = new DataOutputStream(new FileOutputStream(file));
              out.writeShort(area_width);
              out.writeShort(area_height);
              saveType(6);
              saveType(2);
              saveType(12);
              saveType(5);
              saveType(0);
              saveType(1);
              saveType(3);
              saveType(4);
              saveType(7);
              saveType(11);
              saveType(8);
              saveType(9);
              saveType(15);
              saveType(14);
              saveType(13);
              saveType(16);

              out.close();
              setTitle("Level editor - " + file);
   	       }
   	       catch(Exception ex)
   	       {
   	          System.out.println("Can't save file " + file);
   	       }
   	    }
	}
  }

  public void exit() 
  {
    System.exit(0);
  }

  public void helpAbout_actionPerformed(ActionEvent e) 
  {
  }

  void menuNew()
  {
		vObjects = new Vector();
  }

  public boolean action(Event evt, Object obj)
  {
     if (evt.target instanceof Button)
     {
        if (obj.equals(bExit.getLabel()))
        {
           System.exit(0);
        }
        if (obj.equals(bSet.getLabel()))
        {
        	try
        	{
                int x = Integer.parseInt(tfXSize.getText().trim());
                int y = Integer.parseInt(tfYSize.getText().trim());
                if ((x >= 0) && (x <= 220) && (y >= 0) && (y <= 220))
                {
                	area_width = x;
                	area_height = y;
//                	vObjects = new Vector();
    	            pArea.setSize(area_width,area_height);
                }
            }
            catch(Exception ex)
            {
            	tfXSize.setText(area_width + "");
            	tfYSize.setText(area_height + "");
            }
            return true;
        }
     }
     return false;
  }

    Vector parse(String str)
    {
    	String tmp = "";
    	int l = str.length() - 1;
    	v2 = new Vector();
    	for (int i = 0; i <= l; i++)
    	{
    		char c = str.charAt(i);
    		if (i == l) tmp += c;
    		if ((c == ',') || (i == l))
    		{
    			try
    			{
    				v2.addElement(new Integer(Integer.parseInt(tmp)));
    			}
    			catch(Exception ex){}
    			tmp = "";
    		}
    		else tmp += c;
    	}
    	return v2;
    }

    Image img = null;
    Image img2 = null;
    String imgName = "";
    int w1,h1,w2,h2;
    Hashtable hi = null;
    IFrame frm = null;

    IFrame bg = null;
    MediaTracker mt = null;

    IFrame gf(String name)
    {
    	try
    	{
	    	String str = gp(name);
   		 	if (str != null)
	   	 	{
		    	Vector v = parse(str);

  			    str = gp("i" + ((Integer)v.elementAt(0)).intValue());

  			    if (str != null)
  			    {
  			    	if (hi == null) hi = new Hashtable();
  			    	if (mt == null) mt = new MediaTracker(this);;

  			    	if (!(str.equals(imgName)))
  			    	{
  			    		img = null;
  			    		img2 = null;

	  			    	img = Toolkit.getDefaultToolkit().createImage("Res\\" + str + ".png");
	  			    	mt.addImage(img,0);
	  			    	mt.waitForAll();
	  			    	if (img != null) System.out.println(str + ".png ok");
  			    	}
  			    	imgName = str;

			    	w1 = w2 = ((Integer)v.elementAt(3)).intValue();
		   		 	h1 = h2 = ((Integer)v.elementAt(4)).intValue();

		    		if (v.size() > 5) w2 = ((Integer)v.elementAt(5)).intValue();
			    	if (v.size() > 6) h2 = ((Integer)v.elementAt(6)).intValue();
		    		img2 = (Image)hi.get(name);
			    	if (img2 == null)
			    	{
			    		img2 = new BufferedImage(w1,h1,BufferedImage.TYPE_INT_ARGB);
						img2.getGraphics().drawImage(
								img,-((Integer)v.elementAt(1)).intValue(),-((Integer)v.elementAt(2)).intValue(),null);
						hi.put(name,img2);
		    		}
		    		frm = new IFrame(img2,0,0,w1,h1,w2,h2);
	  				return frm;
				}
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		return null;
    }

    String gp(String name)
    {
    	if (hp == null)
    	{
    	    hp = new Hashtable();
            try
            {
	    	    FileInputStream in = new FileInputStream("editor.cfg");
    			char c;
    			int i,mode = 0;
    			String key = "",value = "";
    			while((i = in.read()) != -1)
    			{
    				c = (char)i;
    				if (c == '\n')
    				{
    					mode = 0;
    					if ((key.length() > 0) && (value.length() > 0))
    						hp.put(key.trim().toLowerCase(),value.trim().toLowerCase());
    					key = value = "";
    				}
    				if (mode == 2) continue;
    				if (c == '#')
    				{
    					mode = 2;
    					continue;
    				}
    				if (c == '=')
    				{
    					mode = 1;
    					continue;
    				}
    				if (mode == 0) key += c;
    				if (mode == 1) value += c;
    			}
    			in.close();
    		}
    		catch(Exception e){e.printStackTrace();}
    	}
		return (String)hp.get(name);
    }

}

class MainFrame_menuFileNew_ActionAdapter implements ActionListener 
{
  MainFrame adaptee;

  MainFrame_menuFileNew_ActionAdapter(MainFrame adaptee) 
  {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) 
  {
    adaptee.menuNew();
  }
}

class MainFrame_menuFileOpen_ActionAdapter implements ActionListener 
{
  MainFrame adaptee;

  MainFrame_menuFileOpen_ActionAdapter(MainFrame adaptee) 
  {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) 
  {
    adaptee.open();
  }
}

class MainFrame_menuFileSave_ActionAdapter implements ActionListener 
{
  MainFrame adaptee;

  MainFrame_menuFileSave_ActionAdapter(MainFrame adaptee) 
  {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) 
  {
    adaptee.save();
  }
}

class MainFrame_menuFileExit_ActionAdapter implements ActionListener 
{
  MainFrame adaptee;

  MainFrame_menuFileExit_ActionAdapter(MainFrame adaptee) 
  {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) 
  {
    adaptee.exit();
  }
}

class MainFrame_menuHelpAbout_ActionAdapter implements ActionListener 
{
  MainFrame adaptee;

  MainFrame_menuHelpAbout_ActionAdapter(MainFrame adaptee) 
  {
    this.adaptee = adaptee;
  }

  public void actionPerformed(ActionEvent e) 
  {
    adaptee.helpAbout_actionPerformed(e);
  }
}

class Area_mouseMotionAdapter extends java.awt.event.MouseMotionAdapter
{
  MainFrame adaptee;

  Area_mouseMotionAdapter(MainFrame adaptee)
  {
    this.adaptee = adaptee;
  }

  public void mouseMoved(MouseEvent e)
  {
    adaptee.mouseMovedOnArea(e);
  }
  public void mouseDragged(MouseEvent e)
  {
    adaptee.mouseDraggedOnArea(e);
  }
}
class Area_mouseAdapter extends java.awt.event.MouseAdapter
{
  MainFrame adaptee;
  Area_mouseAdapter(MainFrame adaptee)
  {
    this.adaptee = adaptee;
  }
  public void mousePressed(MouseEvent e)
  {
    adaptee.mousePressedOnArea(e);
  }
  public void mouseReleased(MouseEvent e)
  {
    adaptee.mouseReleasedOnArea(e);
  }
}
class p1_mouseMotionAdapter extends java.awt.event.MouseMotionAdapter
{
  MainFrame adaptee;

  p1_mouseMotionAdapter(MainFrame adaptee)
  {
    this.adaptee = adaptee;
  }

  public void mouseMoved(MouseEvent e)
  {
    adaptee.mouseMovedOnp1(e);
  }
  public void mouseDragged(MouseEvent e)
  {
    adaptee.mouseDraggedOnp1(e);
  }
}
class p1_mouseAdapter extends java.awt.event.MouseAdapter
{
  MainFrame adaptee;
  p1_mouseAdapter(MainFrame adaptee)
  {
    this.adaptee = adaptee;
  }
  public void mousePressed(MouseEvent e)
  {
    adaptee.mousePressedOnp1(e);
  }
  public void mouseReleased(MouseEvent e)
  {
    adaptee.mouseReleasedOnp1(e);
  }
}
class Area_keyAdapter extends java.awt.event.KeyAdapter
{
  MainFrame adaptee;
  Area_keyAdapter(MainFrame adaptee)
  {
    this.adaptee = adaptee;
  }

  public void keyPressed(KeyEvent e)
  {
    adaptee.keyPressedOnArea(e);
  }
}

